package channelParams

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/SyncMap"
	"sync"
)

var (
	deviceKey2Channel sync.Map
)

func SetChannelName(deviceKey string, channelName string) {
	SyncMap.SetValue(&deviceKey2Channel, deviceKey, "channelName", channelName)
}

func SetChannelParam(deviceKey string, channelParam map[string]interface{}) {
	if _, err := SyncMap.GetValue(&deviceKey2Channel, deviceKey, "channelParam"); err != nil {
		return
	}

	SyncMap.SetValue(&deviceKey2Channel, deviceKey, "channelParam", channelParam)
}

func SetChannelLogin(deviceKey string, channelLogin bool) {
	if _, err := SyncMap.GetValue(&deviceKey2Channel, deviceKey, "channelLogin"); err != nil {
		return
	}

	SyncMap.SetValue(&deviceKey2Channel, deviceKey, "channelLogin", channelLogin)
}

func GetChannelLogin(deviceKey string) bool {
	channelLogin, err := SyncMap.GetValue(&deviceKey2Channel, deviceKey, "channelLogin")
	if err != nil || channelLogin == nil {
		return false
	}

	return channelLogin.(bool)
}

func GetChannelName(deviceKey string) (channelName string) {
	val, err := SyncMap.GetValue(&deviceKey2Channel, deviceKey, "channelName")
	if err != nil || val == nil {
		return ""
	}

	return val.(string)
}

func GetChannelParam(deviceKey string) map[string]interface{} {
	val, err := SyncMap.GetValue(&deviceKey2Channel, deviceKey, "channelParam")
	if err != nil || val == nil {
		return nil
	}

	return val.(map[string]interface{})
}

func GetDeviceKeyByChannelName(channelName string) (string, bool) {
	deviceKey := ""
	find := false
	deviceKey2Channel.Range(func(key, value any) bool {
		syncMap := value.(*sync.Map)
		name, err := SyncMap.GetValue(syncMap, "channelName")
		if err != nil {
			return true
		}
		if name == channelName {
			deviceKey = key.(string)
			find = true
			return false
		}

		return true
	})

	return deviceKey, find
}

func HasChannelName(channelName string) bool {
	find := false
	deviceKey2Channel.Range(func(key, value any) bool {
		syncMap := value.(*sync.Map)
		name, err := SyncMap.GetValue(syncMap, "channelName")
		if err != nil {
			return true
		}
		if name == channelName {
			find = true
			return false
		}

		return true
	})

	return find
}

func DelChannelName(channelName string) {
	deviceKey, ok := GetDeviceKeyByChannelName(channelName)
	if !ok {
		return
	}
	deviceKey2Channel.Delete(deviceKey)
}
